package com.store.app;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;
import com.ciwong.libs.widget.CWToast;
import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.model.DBHelper_hy;
import com.hyphenate.easeui.model.recordBean_hy;
import com.store.app.activity.WebViewAdActivity;
import com.store.app.activity.WebViewRegistActivity;
import com.store.app.bean.HXUserBean;
import com.store.app.database.Database;
import com.store.app.database.DatabaseMethod;
import com.store.app.http.Stores;
import com.store.app.http.Submit;
import com.store.app.hyphenate.HyphenateHelper;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.push.PushUtils;
import com.store.app.utils.GoToLogin;
import com.store.app.utils.SettingData;
import com.store.app.utils.TestDeviveInfo;
import com.store.app.utils.ToastUtils;
import com.store.app.utils.Utils;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.TagAliasCallback;

//上面gravity属性的参数：center为居中，center_horizontal为水平居中，center_vertical为垂直居中  
public class MainActivity extends BaseActivity implements IOnHttpListener {
    private Database database;
    private TextView register;
    public static Context context;
    private EditText phone, verification;
    public static Handler handler;
    public static String amount, app_token, security_code, is_admin;
    public static String first_time, member_id, user_token, user_security_code;
    private boolean remember = false;
    private DatabaseMethod method;
    private String error, mobile, account, password;
    private InputMethodManager imm = null;
    private TextView describe;
    CountDownTimer downtimer;
    //数据库存储
    private DBHelper_hy db = null;
    private recordBean_hy rb = null;


    private Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            Message message = new Message();
            message.what = 4;
            handler.sendMessage(message);
        }
    };
    private ProgressDialog progressBar;
    SharedPreferences preferences;
    public static final String PREF_APP_TOKEN = "app_token";
    public static final String PREF_SECURITY_CODE = "security_code";
    public static final String PREF_USER_TOKEN = "user_token";
    public static final String PREF_USER_SECURITY_CODE = "user_security_code";
    public static final String PREF_MEMBER_ID = "member_id";
    public static final String PREF_IS_ADMIN = "is_admin";
    public static float scale;
    private NetRequest netRequest;
    private TextView tvProblem;//登录遇到问题
    private TextView tvRegistNewStore;//注册新店
    private CheckBox cb_xieyi;//是否勾选服务协议
    private TextView tv_xieyi;//服务协议

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        netRequest = new NetRequest(this);
        setContentView(R.layout.activity_main);

        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        ExitApplication.getInstance().addActivity(this);
        context = MainActivity.this;
        database = new Database(context);
        method = new DatabaseMethod(database);
        SDKInitializer.initialize(getApplicationContext());
        // 透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        Intent intent = getIntent();
        String log_again = intent.getStringExtra("log_again");
        List<String> data = method.getData();

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

        Stores.stores_type_key = preferences.getString("stores_type_key", "");
        Stores.business_type_key = preferences.getString("business_type_key", "");
        String user_id = preferences.getString("user_id", "");
        Log.v("zyl","  user_id:"+user_id);
        if(!TextUtils.isEmpty(user_id)){
            LocationApplication.userId = user_id;
        }

        //获取现在版本号比较 新升级就不跳转到主页 并且清空数据
        PackageInfo info = null;
        try {
            info = getPackageManager().getPackageInfo("com.store.app", 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        int currentVersion = info.versionCode;
        int lastVersion = preferences.getInt("versionCode", 0);
        if (currentVersion > lastVersion) {
            SharedPreferences.Editor editor = preferences.edit();
            Log.i("mylog", "新版本退出登陆");
            editor.putInt("versionCode", currentVersion).commit();
            new GoToLogin(this).clearLoginInfo(this);
            if(data!=null) {
                data.clear();
            }
            editor.putString("stores_type_key", "").commit();
            editor.putString("business_type_key", "").commit();
        }

        //跳转到首页或者留着登陆页
        if (data.size() != 0 && log_again == null && !TextUtils.isEmpty(Stores.business_type_key)) {
            goToNext(data);
        } else {
            findViewById(R.id.main_img).setVisibility(View.GONE);
            //未登陆的时候检查版本号
            Log.i("mylog", "登陆页面检查版本222222");
            netRequest.requestCheckVersion(1);

        }
        initLogin(log_again);

        if (db == null) {
            db = new DBHelper_hy(this);
            rb = new recordBean_hy();
        }

    }
    private int times = 0;
    private void initLogin(String log_again) {
        Log.i("zyl", "ddd " + log_again);
        cb_xieyi = (CheckBox) findViewById(R.id.cb_xieyi);
        tv_xieyi = (TextView) findViewById(R.id.ll_user_xieyi);
        register = (TextView) findViewById(R.id.register);

        register.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (TextUtils.isEmpty(phone.getText().toString())) {
                    Toast.makeText(MainActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!Utils.matchPhone(phone.getText().toString())) {
                    Toast.makeText(MainActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(verification.getText().toString())) {
                    Toast.makeText(MainActivity.this, "请输入验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(!cb_xieyi.isChecked()){
                    CWToast.makeText(MainActivity.this, "请确认阅读店东助手协议", Toast.LENGTH_LONG, true)
                            .setToastType(CWToast.TOAST_TYPE_ALERT).show();
                    return;
                }
                imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
                progressBar = new ProgressDialog(view.getContext());
                progressBar.setCancelable(true);
                progressBar.setMessage("登录中...");
                progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progressBar.setProgress(0);
                progressBar.setMax(100);
                progressBar.show();
                account = phone.getText().toString();
                password = verification.getText().toString();
                new Logon(account, password).start();// 网络登录请求的程序
            }
        });

        describe = (TextView) findViewById(R.id.describe);
        downtimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                describe.setText((millisUntilFinished / 1000) + "秒后重发");
            }

            @Override
            public void onFinish() {
                describe.setEnabled(true);
                describe.setText("获取验证码");
            }
        };




        phone = (EditText) findViewById(R.id.phone);
        phone.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(phone.getWindowToken(), 0);
                }
                return true;
            }
        });
        tvProblem = (TextView) findViewById(R.id.tv_problem);
        tvProblem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//				Intent intent = new Intent(MainActivity.this, AcountInfoFeedActivity.class);
//				startActivity(intent);
//                             Intent intent5 = new Intent();
//                intent5.setClass(MainActivity.this, WebViewTGActivity.class);
//                intent5.putExtra("title", "登录遇到问题");
//                intent5.putExtra("url", SettingData.http + SettingData.logintvProblem);
//                startActivity(intent5);



                Intent intent = new Intent(MainActivity.this, WebViewAdActivity.class);
                intent.putExtra("url", SettingData.http + SettingData.logintvProblem);
                intent.putExtra("needX",false);
                startActivity(intent);
            }
        });
        tvRegistNewStore = (TextView) findViewById(R.id.tv_regist_new_store);
        tvRegistNewStore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent5 = new Intent();
                intent5.setClass(MainActivity.this, WebViewRegistActivity.class);
                intent5.putExtra("url", SettingData.registNewStoresURL);
//                intent5.putExtra("url", "http://192.168.16.52:8080/omp-mth-productSpecialist/mobile/stores/app/register");
                startActivity(intent5);

            }
        });
        tv_xieyi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, WebViewAdActivity.class);
                intent.putExtra("url",SettingData.XIEYI);
                intent.putExtra("needX",false);
                startActivity(intent);
            }
        });
        verification = (EditText) findViewById(R.id.verification);
        describe.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (LocationApplication.isNetworkAvailable()) {
                    if (TextUtils.isEmpty(phone.getText().toString())) {
                        Toast.makeText(MainActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (!Utils.matchPhone(phone.getText().toString())) {
                        Toast.makeText(MainActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    describe.setEnabled(false);
                    account = phone.getText().toString();
                    verification.requestFocus();
                    showProgressDialog("加载中...");
                    new register(true).start();
                } else {
                    handler.sendEmptyMessage(2);
                }
            }
        });

        if (LocationApplication.app.getDM().widthPixels < 500) {
            phone.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            describe.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
            verification.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            tvProblem.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
            tvRegistNewStore.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
        }


        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0:

                        if (progressBar != null) {
                            progressBar.dismiss();
                        }
                        Log.v("zyl", "stores_type_key:" + Stores.stores_type_key);
                        Log.v("zyl", "business_type_key:" + Stores.business_type_key);
                        String alias = member_id;
                        Set set = new HashSet();
                        set.add(SettingData.STORES);
                        PushUtils.setTags(MainActivity.this, set, new TagAliasCallback() {
                            @Override
                            public void gotResult(int i, String s, Set<String> set) {

                            }
                        });
                        PushUtils.setAlias(MainActivity.this, alias, new TagAliasCallback() {
                            @Override
                            public void gotResult(int i, String s, Set<String> set) {
                                switch (i) {
                                    case 0:
                                        // 设置成功
                                        break;
                                    case 6002:
                                        //连接超时

                                        break;
                                    default:
                                }
                            }
                        });
                        netRequest.requestJpush(202, "stores", "ANDROID", alias);
//						//联盟为标准版、加盟为高级版
                        if (Stores.stores_type_key.equals(SettingData.HYLX_02)) {
                            Intent intent = new Intent();
                            intent.setClass(MainActivity.this, FunctionHighActivity.class);
                            intent.putExtra("islogintent", true);
                            startActivity(intent);
                            finish();
                        } else if (Stores.stores_type_key.equals(SettingData.HYLX_03)) {
                            Intent intent = new Intent();
                            intent.setClass(MainActivity.this, FunctionHighActivity.class);
                            intent.putExtra("islogintent", true);
                            startActivity(intent);
                            finish();
                        }else if(Stores.stores_type_key.equals(SettingData.HYLX_01)){
                            Intent intent = new Intent();
                            intent.setClass(MainActivity.this, FunctionHighActivity.class);
                            intent.putExtra("islogintent", true);
                            startActivity(intent);
                            finish();
                        }else if(Stores.stores_type_key.equals(SettingData.HYLX_04)){
                            Intent intent = new Intent();
                            intent.setClass(MainActivity.this, FunctionHighActivity.class);
                            intent.putExtra("islogintent", true);
                            startActivity(intent);
                            finish();
                        }



//                        //登录成功之后登录环信
                        netRequest.requestHXIMUserLogin(2, member_id, "stores", Stores.stores_name, "");

                        break;
                    case 1:
                        if (progressBar != null) {
                            progressBar.dismiss();
                        }
                        if (!TextUtils.isEmpty(error)) {
//                            Toast.makeText(MainActivity.this, error,
//                                    Toast.LENGTH_SHORT).show();
                            CWToast.makeText(MainActivity.this, error, Toast.LENGTH_LONG, true)
                                    .setToastType(CWToast.TOAST_TYPE_ALERT).show();
                        }
                        error = "";
//                        try {
//                            downtimer.cancel();
//                            downtimer.onFinish();
//                            describe.setEnabled(true);
//                            describe.setText("获取验证码");
//                        }catch (Exception e){
//                        }
                        dismissProgressDialog();
                        break;
                    case 2:
                        if (progressBar != null) {
                            progressBar.dismiss();
                        }
                        CWToast.makeText(MainActivity.this, "请检查本地网络！", Toast.LENGTH_LONG, true)
                                .setToastType(CWToast.TOAST_TYPE_ALERT).show();
                        break;
                    case 3:
                        Log.v("zyl", "remember:" + remember);
                        if (remember) {
                            new Stores(app_token, member_id, MainActivity.this).start();
                        } else {
                            new AuthType(account).start();
                        }
                        break;
                    case 4:
                        new register(true).start();
                        break;
                    case 5:
                        Log.v("zyl", "登录前：app_token：" + app_token + " mid " + member_id);
                        new QueryStoreInfo(app_token, member_id, MainActivity.this).start();
//						new Stores(app_token,member_id,MainActivity.this).start();
                        break;
                    //获取验证码失败之后，可以重新获取
                    case 6:
                        downtimer.cancel();
                        downtimer.onFinish();
                        describe.setEnabled(true);
                        dismissProgressDialog();
                        break;
                    case 7:
                        if (progressBar != null) {
                            progressBar.dismiss();
                        }
                        showToast("登录失败");
                        break;
                    //获取验证码成功之后开始倒计时
                    case 8:
                        Log.v("zyl", "获取验证码之后开始倒计时");
                        downtimer.start();
                        describe.setEnabled(false);
                        dismissProgressDialog();
                        break;
                    case 9:
                        String msgWhat = (String) msg.obj;
                        if (!TextUtils.isEmpty(msgWhat)) {
                            ToastUtils.showTextToast(MainActivity.this, msgWhat);
                        }
                        break;
                    case 10:
                        String msgWhat10 = (String) msg.obj;
                        if (!TextUtils.isEmpty(msgWhat10)&&!"非法签名".equals(msgWhat10)) {
                            CWToast.makeText(MainActivity.this, msgWhat10, Toast.LENGTH_LONG, true)
                                    .setToastType(CWToast.TOAST_TYPE_ALERT).show();
                        }
                        downtimer.cancel();
                        downtimer.onFinish();
                        describe.setEnabled(true);
                        dismissProgressDialog();
                        break;
                    default:
                        break;
                }
            }
        };
        timer.schedule(task, 7000000, 7000000);


        scale = LocationApplication.app.getDM().density;
        new register(false).start();
        if (!TextUtils.isEmpty(log_again) && log_again.equals("true")) {
//            Toast.makeText(this, "你的账号已在其他设备登录！", Toast.LENGTH_SHORT).show();

        }
    }

    private void goToNext(List<String> data) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.v("zyl", "Stores.stores_type_key************:" + Stores.stores_type_key);
                if (Stores.stores_type_key.equals(SettingData.HYLX_02)) {
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, FunctionHighActivity.class);
                    startActivity(intent);
                    finish();
                } else if (Stores.stores_type_key.equals(SettingData.HYLX_03)) {
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, FunctionHighActivity.class);
                    startActivity(intent);
                    finish();
                } else if(Stores.stores_type_key.equals(SettingData.HYLX_01)){
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, FunctionHighActivity.class);
                    startActivity(intent);
                    finish();
                } else if(Stores.stores_type_key.equals(SettingData.HYLX_04)){
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, FunctionHighActivity.class);
                    startActivity(intent);
                    finish();
                }else {
                    findViewById(R.id.main_img).setVisibility(View.GONE);
                    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putString("stores_type_key", "").apply();
                    return;
                }
            }
        }, 1000);
//        account = data.get(0);
//        password = data.get(1);
//        member_id = data.get(2);
//        user_token= data.get(3);
//        user_security_code = data.get(4);
        user_token = preferences.getString(PREF_USER_TOKEN, "");
        app_token = preferences.getString(PREF_APP_TOKEN, "");
        member_id = preferences.getString(PREF_MEMBER_ID, "");
        security_code = preferences.getString(PREF_SECURITY_CODE, "");
        user_security_code = preferences.getString(PREF_USER_SECURITY_CODE, "");
        Log.v("zyl", "取出来的user_security_code：" + user_security_code);

        remember = true;
        //  new register().start();


    }

    @Override
    public void finish() {
        super.finish();
        Log.v("zyl", "MainActivity finish");
    }

    //dip转px
    public static int dip2px(float dpValue) {

        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 在点击获取验证码控件时，开启该线程，通过参数app_id和private_key从服务器获取app_token
     */
    public class register extends Thread {
        private boolean isgetMemberType;

        public register(boolean isgetMemberType) {
            this.isgetMemberType = isgetMemberType;
        }

        public void run() {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("app_id", SettingData.app_id));
            params.add(new BasicNameValuePair("private_key", SettingData.private_key));
            Log.v("zyl", "SettingData.app_id:" + SettingData.app_id);
            Log.v("zyl", "SettingData.private_key:" + SettingData.private_key);
            JSONObject obj = Submit.submit(params, Stores.http + "/openapi/app/login");
            try {
                String result = obj.getString("rsp_code");
                if (result.equals("succ")) {
                    Log.v("zyl", "获取app_token成功");
                    JSONObject data = obj.getJSONObject("data");
                    app_token = data.getString("app_token");
                    security_code = data.getString("security_code");
                    //is_admin=data.getString("is_admin");
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putString(PREF_APP_TOKEN, app_token).commit();
                    editor.putString(PREF_SECURITY_CODE, security_code).commit();
                    //editor.putString(PREF_IS_ADMIN, is_admin).commit();
                    //if(isgetMemberType) {
                    handler.sendEmptyMessage(3);
                    //}
                } else {
                    error = (String) obj.get("error_msg");
                    Log.v("zyl", "获取app_token失败:" + error);
                    handler.sendEmptyMessage(1);
                }
            } catch (Exception e) {
                Log.v("zyl", "获取apptoken网络不通");
                e.printStackTrace();
                // TODO Auto-generated catch block
//				handler.sendEmptyMessage(2);
            }
        }
    }

    // 登录
    public class Logon extends Thread {
        private String account;
        private String sms_code;

        public Logon(String account, String sms_code) {
            this.account = account;
            this.sms_code = sms_code;
        }


        public void run() {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("app_token", app_token));
            //店东用户
            params.add(new BasicNameValuePair("data_source", "store_assistant"));
            //收银机用户
            //params.add(new BasicNameValuePair("data_source","SJLY_14"));
            params.add(new BasicNameValuePair("device_model", TestDeviveInfo.getDeviceInfo() + ""));
            params.add(new BasicNameValuePair("mobile", account));
            params.add(new BasicNameValuePair("request_info", TestDeviveInfo.getDeviceId(MainActivity.this) + ""));

            params.add(new BasicNameValuePair("sms_code", sms_code));
            Log.v("zyl", "info:" + TestDeviveInfo.getDeviceId(MainActivity.this) + "");
            Log.v("zyl", "device_model:" + TestDeviveInfo.getDeviceInfo() + "");


//			JSONObject paramsObj = new JSONObject();
//			try {
//				paramsObj.put("request_info", TestDeviveInfo.getDeviceId(MainActivity.this)+"");
//				paramsObj.put("device_model", TestDeviveInfo.getDeviceInfo()+"");
//			} catch (JSONException e) {
//				e.printStackTrace();
//			}
//
//			params.add(new BasicNameValuePair("params", paramsObj.toString()));
            Log.v("zyl", "params:" + params.toString());
            String sign = Submit.genPackageSign(params);
            Log.v("zyl", "sign:" + sign);
            params.add(new BasicNameValuePair("sign", sign));
            JSONObject obj = Submit.submit(params, Stores.http + "/openapi/store/login");
            try {
                String result = obj.getString("rsp_code");
                if (result.equals("succ")) {
                    Log.v("zyl", "login succ：" + obj.toString());
                    JSONObject data = obj.getJSONObject("data");

                    user_token = data.getString("user_token");
                    Log.v("zyl", "user_tok:" + user_token);
                    user_security_code = data.getString("security_code");
                    member_id = data.getString("member_id");
                    is_admin = data.getString("is_admin");
                    mobile = data.getString("mobile");
                    String user_id = data.getString("user_id");
                    LocationApplication.userId = user_id;
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putString("user_id", user_id).apply();
                    editor.putString(PREF_USER_TOKEN, user_token).apply();
                    editor.putString(PREF_USER_SECURITY_CODE, user_security_code).apply();
                    editor.putString(PREF_MEMBER_ID, member_id).apply();
                    editor.putString(PREF_IS_ADMIN, is_admin).apply();
                    editor.putString("login_phone", account).apply();//登录时候的账号


//					handler.sendEmptyMessage(5);
                    if (remember) {
                        method.update_data(user_token, app_token, user_security_code, member_id, mobile);
                        handler.sendEmptyMessage(5);
                    } else {
                        method.addtoken(0, user_token, app_token, user_security_code, account, sms_code, member_id);
                        method.addstr("special", "mid", "0");
                        method.addstr("thisimages", "mid", "0");
                        method.addstr("netaddressimages", "mid", "0");
                        //	method.update_site("thisimages", "street_images", "this");
//						handler.sendEmptyMessage(0);
                        handler.sendEmptyMessage(5);
//						netRequest.requestQueryStoresInfo(1);
                    }

                    String alias = "stores_" + member_id;
                    alias = getSharedPreferences("alias", Context.MODE_PRIVATE).getString("alias", "");
                    netRequest.requestJpush(202, "stores", "Android", alias);

                    //登陆成功后，查询是否绑定淘宝账号 --xgp
                    if(!TextUtils.isEmpty(member_id)){
                        netRequest.requestQueryTaoBao(10,member_id,SettingData.STORES);
                    }

                } else {
                    error = (String) obj.get("error_msg");
                    Log.v("zyl", "login fail:" + error);
//					error =  "验证码失效或不存在";
                    handler.sendEmptyMessage(1);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                Log.v("zyl", "登录网络连接错误");
                handler.sendEmptyMessage(2);
            }

        }
    }

    // 验证用户的会员类型
    public class AuthType extends Thread {
        private String account;

        public AuthType(String account) {
            Log.v("zyl", "开始验证会员类型");
            this.account = account;
        }

        public void run() {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("app_token", app_token));

            params.add(new BasicNameValuePair("mobile", account));

            String sign = Submit.genPackageSign(params);
            Log.v("zyl", "签名信息：" + sign);
            params.add(new BasicNameValuePair("sign", sign));
            JSONObject obj = Submit.submit(params, Stores.http + "/openapi/user/valid_store_exist");
            try {
                String result = obj.getString("rsp_code");
                if (result.equals("succ")) {
                    Log.v("zyl", "验证会员类型通过:" + obj.toString());
                    JSONObject jsonObjectData = new JSONObject(obj.getString("data"));
                    String userState = jsonObjectData.getString("user");//用户是否存在
                    String memberState = jsonObjectData.getString("member_type");//是否是会员
//					if(userState.equals("not_exist")){
//						error = "用户不存在";
//						handler.sendEmptyMessage(1);
//						handler.sendEmptyMessage(6);
//					}else{
                    //用户存在
                    if (memberState.equals("not_exist")) {
                        error = "账号不存在";
                        handler.sendEmptyMessage(1);
                        handler.sendEmptyMessage(6);
//                        Intent intent = new Intent(MainActivity.this, AcountInfoFeedActivity.class);
//                        startActivity(intent);
                    } else {
                        //获取短信验证码验证信息
                        netRequest.requestSendSmsCodeMess(3,app_token);

                    }
//					}
                } else {
                    Log.v("zyl", "验证会员类型失败:" + (String) obj.get("error_msg"));
//					handler.sendEmptyMessage(1);
                    Message message = new Message();
                    message.obj = (String) obj.get("error_msg");
                    message.what=10;
                    handler.sendMessage(message);
//					handler.sendEmptyMessage(6);
//                    error = (String) obj.get("error_msg");
//                    handler.sendEmptyMessage(1);
                    //不能加提示 否则会显示非法签名
                    //handler.sendEmptyMessage(6);
                }
            } catch (Exception e) {
                Log.v("zyl", "验证会员类型网络不通");
                // TODO Auto-generated catch block
//				handler.sendEmptyMessage(2);
            }

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exitBy2Click();
            // 调用双击退出函数
        }
        return false;
    }

    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit;
        if (!isExit) {
            isExit = true; // 准备退出
            Toast.makeText(this, "再按一下退出应用", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            ExitApplication.getInstance().exit();
            MainActivity.this.finish();
        }
    }

    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        //查询加盟店信息成功
        if (requestId == 1) {
            Log.v("zyl", "onExecuteSuccess 查询版本信息成功：" + result);
            try {
                JSONObject jsonObjectData = new JSONObject(result);
                int version_code = jsonObjectData.getInt("version_code");
                String version_name = jsonObjectData.getString("version_name");
                final String download_path = jsonObjectData.getString("download_path");
                final String update_content = jsonObjectData.getString("update_content");
                PackageManager pm = MainActivity.this.getPackageManager();
                PackageInfo pi = pm.getPackageInfo(MainActivity.this.getPackageName(), 0);
                int currentVersionCode = pi.versionCode;
                Log.v("zyl", "当前的版本号为：" + currentVersionCode);
                Log.v("zyl", "服务器的版本号为：" + version_code);
                if (currentVersionCode < version_code) {
                    AlertDialog imageDialog = new AlertDialog.Builder(MainActivity.this).setTitle("发现新版本!是否立即更新?").setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                        }
                    }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Log.v("zyl", "download_path:" + download_path);
                            if (!TextUtils.isEmpty(download_path)) {
                                if (isDownloadManagerAvailable(MainActivity.this)) {
                                    Log.v("zyl", "下载器可用");
                                    downLoadPackage(download_path);
                                } else {
                                    doShequClick(download_path);
                                }
                            } else {
                                ToastTools.showShort(MainActivity.this, "下载地址无效!");
                            }
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ToastTools.showShort(MainActivity.this, "当前版本不再支持,请更新到最新版本!");
                            finish();
                        }
                    }).setMessage("更新内容：\n" + update_content).show();

                    imageDialog.setCancelable(false);


                    Log.v("zyl", "当前的版本号小于服务器的版本号,需要更新");

//                Uri uri = Uri.parse(download_path);
//                Intent viewIntent = new Intent(Intent.ACTION_VIEW,uri);
//                WebViewActivity.this.startActivity(viewIntent);
                } else {
                    Log.v("zyl", "当前的版本已经是最新版本");
                }
            } catch (Exception e) {
            }
        } else if (requestId == 2) {
            Gson gson = new Gson();
            HXUserBean hxUserBean = gson.fromJson(result, HXUserBean.class);
            String im_user_id = hxUserBean.getIm_user_id();
            if (!TextUtils.isEmpty(im_user_id)) {
                Log.v("zyl", "环信id:" + im_user_id);
//                netRequest.requestHXModifyIMUserInfo(3,im_user_id,"","","http://tx.haiqq.com/uploads/allimg/150321/10563HC7-5.jpg","","");
                login(im_user_id);
                rb.saveMember(db, MainActivity.member_id, im_user_id, Stores.stores_name
                        , "", "", "2");
                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("im_user_id", im_user_id).apply();
                LocationApplication.im_user_id = im_user_id;
            } else {
                Log.i("zyl", "获取环信id失败");
            }
        } else if (requestId == 202) {
            Log.d("lxp", "发送成功");

        }else if(requestId == 10){
            Log.d("xgp", "登陆 querySuccess:" + result);
            try {
                //解析服务器返回的用户绑定的淘宝账户信息
                JSONObject jsonObject = new JSONObject(result);
                JSONArray taoBaojsonArray = jsonObject.getJSONArray("list");
                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
                SharedPreferences.Editor editor = preferences.edit();
                if(taoBaojsonArray.length() == 0){
                    editor.putString("account_id","").apply();
                    editor.putString("account_no","").apply();
                }else{
                    JSONObject taoBaojsonObject = taoBaojsonArray.getJSONObject(0);
                    String account_id = taoBaojsonObject.getString("account_id");
                    String account_no = taoBaojsonObject.getString("account_no");
                    Log.d("xgp", "account_id:" + account_id);
                    Log.d("xgp", "account_no:" + account_no);
                    //将用户绑定的淘宝账户信息存储到SP文件中
                    editor.putString("account_id",account_id).apply();
                    editor.putString("account_no",account_no).apply();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }else if (requestId == 3) {
            //获取短信验证码验证信息
            if(TextUtils.isEmpty(result)) {
                showToast("获取短信验证码失败，请稍后重试！");
            }else{
                //获取短信验证码
                handler.sendEmptyMessage(8);
                netRequest.requestSendSmsCode(4,app_token,account,result);
            }
        }else if (requestId == 4) {
            //获取短信验证码成功
        }


    }

    public void login(final String s_name) {
        EMClient.getInstance().login(s_name, s_name, new EMCallBack() {

            @Override
            public void onSuccess() {
                Log.v("zyl", "登录环信成功");
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
            }

            @Override
            public void onProgress(int progress, String status) {
                Log.d("mylog", "login: " + progress);
            }

            @Override
            public void onError(final int code, final String message) {
                Log.v("zyl", "登录环信失败");
                loginAgain(s_name);
            }
        });
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        //查询加盟店信息失败
        if (requestId == 1) {
            Log.v("zyl", "onExecuteFail 查询版本信息失败：" + msg);
        } else if (requestId == 2) {
            Log.v("zyl", "onExecuteFail 环信登录失败：" + msg);
        }else if (requestId == 3) {
            //获取短信验证码验证信息失败
            error = msg;
            handler.sendEmptyMessage(1);
            handler.sendEmptyMessage(6);
        }else if (requestId == 4) {
            //获取短信验证码失败
            error = msg;
            handler.sendEmptyMessage(1);
            handler.sendEmptyMessage(6);
        }

    }


    public class QueryStoreInfo extends Thread {


        private Context context;

        public QueryStoreInfo(String app_token, String member_id, Context context) {
            Stores.app_token = app_token;
            Stores.member_id = member_id;
            this.context = context;
        }

        public void run() {

            try {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("app_token", Stores.app_token));
                JSONObject paramsone = new JSONObject();
                paramsone.put("member_id", Stores.member_id);
                params.add(new BasicNameValuePair("params", paramsone.toString()));
                params.add(new BasicNameValuePair("service", "member.storeFind"));
                String sign = Submit.genPackageSign(params);
                params.add(new BasicNameValuePair("sign", sign));
                JSONObject obj = Submit.submit(params, Stores.http + "/openapi/member");
                Log.i("mylog", "ssss " + obj.toString());
                String result = obj.getString("rsp_code");
                if (result.equals("succ")) {
                    JSONObject data = obj.getJSONObject("data");
                    Log.v("zyl", "查询资料成功:" + data);
                    Stores.area_id = data.getString("area_id");  //配送范围
                    Stores.area_desc = data.getString("area_desc");//配送范围
                    Stores.area_desc = Stores.area_desc.replace("中国,", "").replace(",", "");
                    Stores.stores_name = data.getString("stores_name");//加盟店名称
//					Log.v("zyl","加盟店名称："+stores_name);
                    Stores.stores_type_key = data.getString("stores_type_key");//加盟店商业类别
                    Stores.store_desc = data.getString("desc1");//加盟店商业类别
                    Stores.business_type_key = data.getString("business_type_key");//门店商业类型
                    Stores.contact_person = data.getString("contact_person");//联系人(店主)
                    Stores.contact_tel = data.getString("contact_tel");//联系电话
                    Stores.address = data.getString("address");//详细地址
                    Stores.neighbor_pic_path = data.getString("neighbor_pic_path");
                    Stores.longitude = data.getString("longitude");//经度
                    Stores.latitude = data.getString("latitude");//维度
                    Stores.activity_servcie = data.getString("activity_servcie");//提供的服务
                    if (!TextUtils.isEmpty(Stores.activity_servcie)) {
                        Stores.activity_servcie = Stores.activity_servcie.substring(1, Stores.activity_servcie.length() - 1);
                        Stores.activity_servcie = Stores.activity_servcie.replaceAll(" ", "");
                    }

                    if (!TextUtils.isEmpty(Stores.activity_servcie)) {
                        String[] sourceStrArray = Stores.activity_servcie.split(",");
                        if (Stores.type_service != null) {
                            Stores.type_service.clear();
                        }
                        for (int i = 0; i < sourceStrArray.length; i++) {
                            Stores.type_service.add(Integer.valueOf(sourceStrArray[i]).intValue());//Integer.parseInt(sourceStrArray[i]));
                        }
                    }


                    //保存店铺资料
                    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putString("member_id", Stores.member_id).apply();
                    editor.putString("area_id", Stores.area_id).apply();
                    editor.putString("area_desc ", Stores.area_desc).apply();
                    editor.putString("stores_name", Stores.stores_name).apply();
                    editor.putString("store_desc", Stores.store_desc).apply();
                    editor.putString("contact_person", Stores.contact_person).apply();
                    editor.putString("stores_type_key", Stores.stores_type_key).apply();
                    editor.putString("business_type_key", Stores.business_type_key).apply();
                    editor.putString("contact_tel", Stores.contact_tel).apply();
                    editor.putString("address", Stores.address).apply();
                    editor.putString("neighbor_pic_path", Stores.neighbor_pic_path).apply();
                    editor.putString("longitude", Stores.longitude).apply();
                    editor.putString("latitude", Stores.latitude).apply();
                    editor.putString("activity_servcie", Stores.activity_servcie).apply();
                    handler.sendEmptyMessage(0);
                } else {
                    Log.v("zyl", "查询资料失败:" + obj.getString("error_msg"));
                    if (context != null) {
                        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
                        if (!TextUtils.isEmpty(member_id) && member_id.equals(preferences.getString("member_id", ""))) {
                            Stores.area_id = preferences.getString("area_id", "");
                            Stores.area_desc = preferences.getString("area_desc", "");
                            Stores.stores_name = preferences.getString("stores_name", "");
                            Stores.store_desc = preferences.getString("store_desc", "");
                            Stores.stores_type_key = preferences.getString("stores_type_key", "");
                            Stores.business_type_key = preferences.getString("business_type_key", "");
                            Stores.contact_person = preferences.getString("contact_person", "");
                            Stores.contact_tel = preferences.getString("contact_tel", "");
                            Stores.address = preferences.getString("address", "");
                            Stores.neighbor_pic_path = preferences.getString("neighbor_pic_path", "");
                            Stores.longitude = preferences.getString("longitude", "");
                            Stores.latitude = preferences.getString("latitude", "");
                            Stores.activity_servcie = preferences.getString("activity_servcie", "");
                            if (!Stores.activity_servcie.equals("")) {
                                if (Stores.type_service != null) {
                                    if (Stores.type_service.size() == 0) {
                                        String[] sourceStrArray = Stores.activity_servcie.split(",");
                                        for (int i = 0; i < sourceStrArray.length; i++) {
                                            Stores.type_service.add(Integer.valueOf(sourceStrArray[i]).intValue());//Integer.parseInt(sourceStrArray[i]));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    handler.sendEmptyMessage(7);
                }

            } catch (Exception e) {
                e.printStackTrace();
                Log.v("zyl", "查询资料网络错误");
                Log.v("mylog", "查询资料网络错误");
                handler.sendEmptyMessage(2);
            }
        }
    }

    //登录错误的情况下先调退出接口再登录一次
    public void loginAgain(final String s_name) {
        HyphenateHelper.getInstance().logout(false, new EMCallBack() {

            @Override
            public void onSuccess() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                EMClient.getInstance().login(s_name, s_name, new EMCallBack() {

                    @Override
                    public void onSuccess() {
                        Log.i("zyl", "再次登录环信成功");
                        // ** manually load all local groups and conversation
                        EMClient.getInstance().groupManager().loadAllGroups();
                        EMClient.getInstance().chatManager().loadAllConversations();

                    }

                    @Override
                    public void onProgress(int progress, String status) {
                    }

                    @Override
                    public void onError(final int code, final String message) {

                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {

            }
        });

    }

    public void doShequClick(final String downloadurl) {
        try {
            Uri uri = Uri.parse(downloadurl);
            Intent browserIntent = new Intent(Intent.ACTION_VIEW);
            browserIntent.setDataAndType(uri, "text/html");
            browserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
            startActivity(browserIntent);
            finish();
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "请到腾讯应用宝更新最新安装包!", Toast.LENGTH_SHORT).show();
            finish();
        }
    }


    private volatile ProgressDialog mProgressDialog;

    protected void showProgressDialog(String msg) {
        if (mProgressDialog == null || !mProgressDialog.getContext().equals(this)) {
            mProgressDialog = new ProgressDialog(this);
        }
        mProgressDialog.setMessage(msg);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
    }

    protected void dismissProgressDialog() {
        if (mProgressDialog != null)
            mProgressDialog.dismiss();
    }
}